<template>
  <van-icon
    :name="value === 1 ? 'good-job' : 'good-job-o'"
    :color="value === 1 ? '#e5645f' : ''"
    :loading="loading"
    @click="onCollect"
  />
  <!-- article 中的 attitude 表示用户对文章的态度
- -1 无态度
- 0 不喜欢
- 1 已点赞 -->
</template>

<script>
import { addLike, deleteLike } from '../../api/article'
export default {
  name: 'LikeArticle',
  data () {
    return { loading: false }
  },
  props: {
    value: {
      type: Number,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    async onCollect () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中',
        forbidClick: true // 是否禁止背景点击
      })
      try {
        let status = -1
        if (this.value === 1) {
          // 取消点赞
          await deleteLike(this.articleId)
        } else {
          // 点赞
          await addLike(this.articleId)
          status = 1
        }
        this.$emit('input', status)
        this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
      } catch (error) {
        this.$toast.fail('操作失败，请重新操作')
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
